package com.godfrey.service.impl;

import com.godfrey.pojo.User;
import com.godfrey.repository.UserRepository;
import com.godfrey.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 服务实现层
 *
 * @author godfrey
 * @date 2020-07-23
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User save(User user) {
        return userRepository.save(user);
    }

    @Override
    public void deleteById(Integer userId) {
        userRepository.deleteById(userId);
    }

    @Override
    public User updateUser(Integer userId, User user) {
        user.setId(userId);
        return userRepository.saveAndFlush(user);
    }

    @Override
    public User getUserInfo(Integer userId) {
        Optional<User> optional = userRepository.findById(userId);
        return optional.orElseGet(User::new);
    }

    @Override
    public Page<User> pageQuery(Integer pageNum, Integer pageSize) {
        return userRepository.findAll(PageRequest.of(pageNum - 1, pageSize));
    }
}
